package m

import (
	"GameServer/Common/utils"
	"encoding/json"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"

	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"
)

type UnionEnergy struct {
	BaseM
	Uid        bson.ObjectId      `bson:"_id" json:"_id"`
	ReqMsg     *ChatMsg           `bson:"reqMsg" json:"reqMsg"`
	Energy     int64              `bson:"energy" json:"energy"`
	EnergyTime int64              `bson:"energyTime" json:"energyTime"`
	Recvs      []*UnionEnergyRecv `bson:"recvs,omitempty" json:"recvs"`
	Sends      []*UnionEnergySend `bson:"sends,omitempty" json:"sends"`
}

// 收到的赠送
type UnionEnergyRecv struct {
	Uid         string `bson:"uid" json:"uid"`
	Name        string `bson:"name" json:"name"`
	Head        string `bson:"head" json:"head"`
	EnergyNum   int64  `bson:"energyNum" json:"energyNum"`
	Status      int64  `bson:"status" json:"status"`
	Time        int64  `bson:"time" json:"time"`
	AvatarFrame int64  `bson:"avatarFrame" json:"avatarFrame"`
}

// 发出的赠送
type UnionEnergySend struct {
	Uid         string `bson:"uid" json:"uid"`
	Mid         string `bson:"mid" json:"mid"`
	RefreshTime int64  `bson:"refreshTime" json:"refreshTime"`
}

func NewUnionEnergy() cache.EntryI {
	return &UnionEnergy{
		Recvs: make([]*UnionEnergyRecv, 0),
		Sends: make([]*UnionEnergySend, 0),
	}
}

func (this *UnionEnergy) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("unionEnergy", bson.M{"_id": this.Uid}, this)
	if err != nil {
		return
	}
	return
}

func (this *UnionEnergy) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		this.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		this.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "UnionEnergy_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return this.LoadData()
}

func (this *UnionEnergy) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("unionEnergy", bson.M{"_id": this.Uid}, nil, &this)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	return
}

// 更新数据
func (this *UnionEnergy) Update(val *UnionEnergy) {
	Cache.Put("unionEnergy", this.Uid.Hex(), val)
	val.UpdateData()
}

func (this *UnionEnergy) AddRecv(val *UnionEnergyRecv) {
	defer this.Update(this)
	this.Recvs = append(this.Recvs, val)

	cMsg := new(ChatExt)
	json.Unmarshal([]byte(this.ReqMsg.Ext), &cMsg)

	cMsg.Current += val.EnergyNum
	if cMsg.Total < cMsg.Current {
		cMsg.Current = cMsg.Total
	}
	this.ReqMsg.Ext = cMsg.String()
}

func (this *UnionEnergy) AddSends(val *UnionEnergySend) {
	defer this.Update(this)
	if len(this.Sends) >= 500 {
		this.Sends = append(this.Sends[1:], val)
		return
	}
	this.Sends = append(this.Sends, val)
}

func (this *UnionEnergy) UpdataChatMsg(recv *UnionEnergyRecv) {

}

func (this *UnionEnergy) SendList() (r []*UnionEnergySend) {
	return this.Sends
}

func (this *UnionEnergy) IsSend(tuid string, mid string) bool {
	for _, item := range this.Sends {
		if item.Uid == tuid && mid == item.Mid {
			return true
		}
	}
	return false
}

// 赠送体力同时是否还能够获得体力
func (this *UnionEnergy) IsCanGetEnergy() bool {
	now := utils.TNow()

	old := utils.TTime(this.EnergyTime, 0)

	if now.Year() == old.Year() && now.Month() == old.Month() && now.Day() == old.Day() {
		if this.Energy >= 50 {
			return false
		}
		return true
	}
	this.Energy = 0
	return true
}

//赠送体力 添加 自己获得一点体力
func (this *UnionEnergy) AddCanGetEnergy(num int64) {
	defer this.Update(this)
	this.EnergyTime = utils.TNow().Unix()
	this.Energy += num
}

func (this *UnionEnergy) Reset(msgChat *ChatMsg) {
	nEnergy := &UnionEnergy{Uid: this.Uid, ReqMsg: msgChat, Recvs: make([]*UnionEnergyRecv, 0), Sends: make([]*UnionEnergySend, 0)}
	this.Update(nEnergy)
}

// 清空用户请求的体力信息
func (this *UnionEnergy) Clear() {
	nEnergy := &UnionEnergy{Uid: this.Uid, Recvs: make([]*UnionEnergyRecv, 0), Sends: make([]*UnionEnergySend, 0)}
	this.Update(nEnergy)
}

func (u *User) GetUnionEnergy() (r *UnionEnergy) {
	v, _ := Cache.Get("unionEnergy", u.Uid.Hex())
	r = v.(*UnionEnergy)
	return
}
